package com.igoal.service.dwr;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.WebContextFactory;
import org.springframework.security.context.SecurityContextHolder;

import com.igoal.common.SessionConstants;
import com.igoal.dto.UserDTO;

public class BaseDWRService {
	protected Log logger;
	
	public String getUserInSession(){
		return SecurityContextHolder.getContext().getAuthentication().getName();
	}
	
	protected boolean isLoginUser(){
		String userInSession = getUserInSession();
		return !userInSession.equalsIgnoreCase("roleAnonymous");
	}
	
	/**
	 * In case use ajax only
	 * @return user session {@link UserDTO}
	 */
	@Deprecated
	protected UserDTO getUserSessionByUsingDWRWebContext(){
		HttpSession session = WebContextFactory.get().getSession();		
		if(session == null) return null;
		
		Object userSession = session.getAttribute(SessionConstants.USER_SESSION);
		if(userSession != null){
			UserDTO user = (UserDTO) userSession;
			debug("Get user["+user.getUsername()+"] in session.");
			return user;
		}		
		debug("There's not any user in session.");
		return null;
	}
	
	@Deprecated
	protected void setUserSession(UserDTO userDTO){
		WebContextFactory.get().getSession(true).setAttribute(SessionConstants.USER_SESSION, userDTO);
	}
	
	@Deprecated
	protected void removeUserSession(){
		HttpSession session = WebContextFactory.get().getSession(false);
		if(session != null){
			session.removeAttribute(SessionConstants.USER_SESSION);
		}
	}
	
	protected void debug(Object message){
		checkLoggerExist();
		if(logger.isDebugEnabled()){
			logger.debug(message);
		}
	}
	
	protected void debug(Object message, Throwable throwable){
		checkLoggerExist();
		if(logger.isDebugEnabled()){
			logger.debug(message, throwable);
		}
	}
	
	protected void error(Object message){
		checkLoggerExist();
		logger.error(message);
	}
	
	protected void error(Object message, Throwable throwable){
		checkLoggerExist();
		logger.error(message, throwable);
	}
	
	private void checkLoggerExist(){
		if(logger == null){
			logger = LogFactory.getLog(this.getClass());
		}
	}
}
